package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.common.Constants;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    private final StringRedisTemplate stringRedisTemplate;

    private final UserServiceImpl userService;

    private final IFollowService followService;

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录的用户
        UserDTO user = UserHolder.getUser();
        // 保存博客
        blog.setUserId(user.getId());
        boolean save = this.save(blog);
        if (!save) {
            log.warn("博客 {} 保存失败", blog.getId());
            return Result.fail("新增笔记失败");
        }
        // 现在发完博客之后，采用推的模式将博客推给当前用户的所有粉丝
        // 1. 获取当前用户所有粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 2. 将博客id存入到用户收件箱中，收件箱使用redis实现
        follows.forEach(follow -> {
            String key = "feed" + follow.getUserId();
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        });

        return Result.ok(blog.getId());
    }

    @Override
    public Result likeBlog(Long id) {
        // 获取点赞的用户
        UserDTO user = UserHolder.getUser();
        // 查看当前用户是否已经点过赞
        Double score = stringRedisTemplate.opsForZSet().score(Constants.BLOG_LIKE + id, user.getId().toString());
        // 说明没点过赞，点赞后点赞数+1，并将用户加入到zset中，分数为时间戳
        if (score == null) {
            boolean success = this.update().eq("id", id).setSql("liked = liked + 1").update();
            if (success) {
                stringRedisTemplate.opsForZSet().add(Constants.BLOG_LIKE + id, user.getId().toString(), System.currentTimeMillis());
            }
        }
        else {
            boolean success = this.update().eq("id", id).setSql("liked = liked - 1").update();
            if (success) {
                stringRedisTemplate.opsForZSet().remove(Constants.BLOG_LIKE + id, user.getId().toString());
            }
        }

        return Result.ok();
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 按照点赞数从大到小排序，获取所有blog
        Page<Blog> hotBlogPage = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 博客要显示作者信息
        List<Blog> records = hotBlogPage.getRecords();
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setIcon(user.getIcon());
            blog.setName(user.getNickName());
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = this.getById(id);
        if (blog == null) {
            return Result.fail("博客不存在");
        }
        User user = userService.getById(blog.getUserId());
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // 查看博客点赞前五的用户
        Set<String> range = stringRedisTemplate.opsForZSet().range(Constants.BLOG_LIKE + id, 0, 4);
        // 解析出用户
        if (range == null) {
            return Result.ok(Collections.emptyList());
        }
        ArrayList<UserDTO> userDTOList = new ArrayList<>();
        range.forEach(s -> {
            Long userId = Long.parseLong(s);
            User user = userService.getById(userId);
            UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
            userDTOList.add(userDTO);
        });

        return Result.ok(userDTOList);
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        UserDTO user = UserHolder.getUser();
        String feedKey = "feed" + user.getId();
        Set<ZSetOperations.TypedTuple<String>> blogIdWhitScore = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(feedKey, 0, max, offset, SystemConstants.MAX_PAGE_SIZE);
        if (blogIdWhitScore == null ||blogIdWhitScore.isEmpty()) {
            return Result.ok();
        }
        ArrayList<String> blogIdList = new ArrayList<>();
        long minTime = 0L;
        int os = 0;
        for (ZSetOperations.TypedTuple<String> item : blogIdWhitScore) {
            blogIdList.add(item.getValue());
            long time = Objects.requireNonNull(item.getScore()).longValue();
            if (time == minTime) {
                os++;
            }
            else {
                minTime = time;
                os = 1;
            }
        }
        ArrayList<Blog> blogArrayList = new ArrayList<>();
        blogIdList.forEach(blogId -> {
            Blog blog = getById(blogId);
            blogArrayList.add(blog);
            isBlogLiked(blog);
        });

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogArrayList);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);
        return Result.ok(blogArrayList);
    }

    public void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        // 博客没登录时也可以查看
        if (user == null)
            return;
        Double score = stringRedisTemplate.opsForZSet().score(Constants.BLOG_LIKE + blog.getId(), user.getId().toString());
        blog.setIsLike(score != null);
    }
}
